package com.yu.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yu.app.mapper.GoodsCategoryMapper;
import com.yu.app.mapper.GoodsMapper;
import com.yu.app.mapper.GoodsPropertyMapper;
import com.yu.app.mapper.OrderGoodsMapper;
import com.yu.app.pojo.Goods;
import com.yu.app.pojo.GoodsCategory;
import com.yu.app.pojo.GoodsProperty;
import com.yu.app.pojo.OrderGoods;
import com.yu.app.pojo.vo.GoodsMenuVO;
import com.yu.app.pojo.vo.GoodsVO;
import com.yu.app.pojo.vo.SameCategoryPropertyVO;
import com.yu.app.service.GoodsService;
import com.yu.common.constant.Const;
import com.yu.common.enums.GoodsPropertyCategory;
import com.yu.common.service.LockService;
import com.yu.common.service.RedisService;
import com.yu.common.service.cache.LocalCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class GoodsServiceImpl implements GoodsService {
    @Resource
    private GoodsCategoryMapper goodsCategoryMapper;
    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private OrderGoodsMapper orderGoodsMapper;
    @Resource
    private GoodsPropertyMapper goodsPropertyMapper;
    @Resource
    private RedisService redisService;
    @Resource
    private LockService lockService;

    // 获取商品菜单列表
//    public List<GoodsMenuVO> getGoodsMenusVOList() {
//        log.info("[定时任务] 检查商品的属性表是否合法并进行校验");
//        goodsPropertyMapper.setIsDefaultFalse(); // 加料属性全部设置为非默认
//        List<GoodsCategory> categoryList = goodsCategoryMapper.selectList(null);
//        List<GoodsMenuVO> goodsMenuVOS = new ArrayList<>();
//        for (GoodsCategory category : categoryList) { // 商品菜单栏
//            GoodsMenuVO goodsMenuVO = new GoodsMenuVO();
//            goodsMenuVO.setGoodsCategoryName(category.getName());
//            goodsMenuVO.setGoodsCategoryShow(category.getShowStatus());
//            goodsMenuVO.setDisplayOrder(category.getDisplayOrder());
//            goodsMenuVO.setGoodsList(getGoodsVoOfSameCategory(category.getName()));
//            goodsMenuVOS.add(goodsMenuVO);
//        }
//        // 排序
//        goodsMenuVOS.sort((e1, e2) -> {
//            return e1.getDisplayOrder() - e2.getDisplayOrder();
//        });
//        return goodsMenuVOS;
//    }
//
//    // 获取每个菜单类的商品，category = [‘大小’, '温度'...]
//    public List<GoodsVO> getGoodsVoOfSameCategory(String category) {
//        List<Goods> goodsOfSameCategory = goodsMapper.selectList(new QueryWrapper<Goods>()
//                .eq("goods_category_name", category));
//        List<GoodsVO> goodsVOSOfSameCategory = new ArrayList<>(goodsOfSameCategory.size());
//        for (Goods goods : goodsOfSameCategory) {
//            GoodsVO goodsVO = new GoodsVO();
//            BeanUtils.copyProperties(goods, goodsVO);
//            goodsVO.setNumber(0);
//            // 同类属性 如：大小
//            List<GoodsProperty> allProperties = goodsPropertyMapper.selectList(
//                    new QueryWrapper<GoodsProperty>().eq("goods_id", goods.getId()));
//            HashMap<String, List<GoodsProperty>> map = new HashMap<>();
//            for (GoodsProperty property : allProperties) {  // eg: {大小: ['', '', ''], 温度: ['', '', '']}
//                if (!map.containsKey(property.getCategory()))
//                    map.put(property.getCategory(), new ArrayList<>());
//                map.get(property.getCategory()).add(property);
//                // 根据默认的大杯还是小杯还是中杯来重置默认价格
//                if (GoodsPropertyCategory.ENUM_size.text.equals(property.getCategory()) && property.getIsDefault()) {
//                    goodsVO.setDefaultPrice(property.getRebasePrice());
//                    goods.setDefaultPrice(property.getRebasePrice());
//                }
//            }
//            goodsVO.setRealPrice(goodsVO.getDefaultPrice());
//            goodsMapper.updateById(goods); // 更新商ping的默认价格
//            List<SameCategoryPropertyVO> goodsPropertyVos = new ArrayList<>();
//            for (String propertyCategory : map.keySet()) { // 将HashMap的Entry转换成对象 [{'大小', [属性表]}, {...}]
//                SameCategoryPropertyVO sameCategoryPropertyVO = new SameCategoryPropertyVO();
//                sameCategoryPropertyVO.setCategory(propertyCategory);
//                sameCategoryPropertyVO.setRequired(!GoodsPropertyCategory.ENUM_jia_liao.text.equals(propertyCategory)); // 除了加料 其他都是必选
//                sameCategoryPropertyVO.setPropertyList(map.get(propertyCategory));
//                goodsPropertyVos.add(sameCategoryPropertyVO);
//
//            }
//            // 检验并纠正商品的每个属性是否合法
//            goodsVO.setGoodsPropertyVos(goodsPropertyVos);
//            goodsVOSOfSameCategory.add(goodsVO);
//        }
//        // 排序
//        goodsVOSOfSameCategory.sort((e1, e2) -> {
//            return e1.getDisplayOrder() - e2.getDisplayOrder();
//        });
//        return goodsVOSOfSameCategory;
//    }

    @Override
    public Object getGoodsMenuDetailList() {
        List<GoodsMenuVO> list = LocalCache.get(Const.CONST_goods_menu_vo_cache);
        if (!CollectionUtils.isEmpty(list))
            return list;

        // TODO 乐观锁 让一个请求去请求数据库 其他锁住, 锁10秒自动释放
        if (!lockService.tryLock(Const.CONST_lock_redis_prefix + Const.CONST_goods_menu_vo_cache, "", 10))
            return new ArrayList<>();

        List<GoodsCategory> goodsCategoryList = goodsCategoryMapper.selectList(null);
        // 使用2个map去关联关系
        HashMap<String, List<Goods>> sameCategoryGoodsMap = new HashMap<>(goodsCategoryList.size());
        HashMap<String, GoodsMenuVO> goodsMenuVOMap = new HashMap<>(goodsCategoryList.size());
        for (GoodsCategory goodsCategory : goodsCategoryList) {
            sameCategoryGoodsMap.put(goodsCategory.getName(), new ArrayList<>());
            GoodsMenuVO goodsMenuVO = new GoodsMenuVO();
            goodsMenuVO.setGoodsCategoryName(goodsCategory.getName());
            goodsMenuVO.setGoodsCategoryName(goodsCategory.getName());
            goodsMenuVO.setDisplayOrder(goodsCategory.getDisplayOrder());
            goodsMenuVO.setGoodsCategoryShow(goodsCategory.getShowStatus());
            goodsMenuVOMap.put(goodsCategory.getName(), goodsMenuVO);
        }

        List<Goods> allGoods = goodsMapper.selectList(null);
        // 将所有商品分类
        for (Goods good : allGoods) {
            if (sameCategoryGoodsMap.containsKey(good.getGoodsCategoryName()))
                sameCategoryGoodsMap.get(good.getGoodsCategoryName()).add(good);
        }

        // 关联同类商品排好序后放到到对应的类别里
        for (Map.Entry<String, GoodsMenuVO> goodsMenuVOEntry : goodsMenuVOMap.entrySet()) {
            List<Goods> sameCategoryGoodsList = sameCategoryGoodsMap.get(goodsMenuVOEntry.getKey());
            sameCategoryGoodsList.sort((o1, o2) -> o1.getDisplayOrder() - o2.getDisplayOrder());
            List<GoodsVO> goodsVos = new ArrayList<>();
            // 填充商品的属性
            for (Goods goods : sameCategoryGoodsList) {
                List<GoodsProperty> goodsPropertyList = goodsPropertyMapper.selectList(
                        new QueryWrapper<GoodsProperty>().eq("goods_id", goods.getId()));
                HashMap<String, List<GoodsProperty>> propertyMap = new HashMap<>();
                for (GoodsProperty goodsProperty : goodsPropertyList) {
                    if (propertyMap.containsKey(goodsProperty.getCategory())) {
                        propertyMap.get(goodsProperty.getCategory()).add(goodsProperty);
                    } else {
                        propertyMap.put(goodsProperty.getCategory(), new ArrayList<GoodsProperty>() {{
                            add(goodsProperty);
                        }});
                    }
                }
                List<SameCategoryPropertyVO> goodsPropertyVos = new ArrayList<>();
                for (Map.Entry<String, List<GoodsProperty>> entry : propertyMap.entrySet()) {
                    // 属性类别->属性列表  转换成对象
                    SameCategoryPropertyVO goodsPropertyVo = new SameCategoryPropertyVO();
                    goodsPropertyVo.setCategory(entry.getKey());
                    goodsPropertyVo.setRequired(!"加料".equals(entry.getKey()));
                    goodsPropertyVo.setPropertyList(entry.getValue());
                    goodsPropertyVos.add(goodsPropertyVo);
                }
                GoodsVO goodsVo = new GoodsVO();
                BeanUtils.copyProperties(goods, goodsVo);
                goodsVo.setGoodsPropertyVos(goodsPropertyVos);
                goodsVo.setRealPrice(goodsVo.getDefaultPrice());
                goodsVos.add(goodsVo);
            }
            goodsMenuVOEntry.getValue().setGoodsList(goodsVos);
        }

        List<GoodsMenuVO> goodsMenuVOList = new ArrayList<>(goodsMenuVOMap.values());
        // 最后对菜单进行排序
        goodsMenuVOList.sort((o1, o2) -> o1.getDisplayOrder() - o2.getDisplayOrder());

        log.info("缓存到java内存: " + goodsCategoryList);
        LocalCache.set(Const.CONST_goods_menu_vo_cache, goodsMenuVOList, Const.CONST_one_hour);
        return goodsMenuVOList;
    }

    // 订单所有商品
    @Override
    public List<OrderGoods> getOrderGoodsList(String orderNo) {
        return orderGoodsMapper.selectList(new QueryWrapper<OrderGoods>().eq("order_no", orderNo));
    }
}
